package com.thememaker.lockstyle;

import com.alibaba.fastjson.JSON;
import com.jfoenix.controls.JFXComboBox;
import com.thememake.Constants;
import com.thememake.common.Context;
import com.thememake.entity.ThemeFileInfo;
import com.thememake.ui.R;
import com.thememake.ui.Toast;
import com.thememake.ui.dialog.ProgressDialog;
import com.thememake.ui.dialog.SBTFxDialog;
import com.thememake.util.FileUtils;
import com.thememaker.lockstyle.bean.action.LaunchPad;
import com.thememaker.lockstyle.bean.command.IntentCommand;
import com.thememaker.lockstyle.control.LayoutComponentUtils;
import com.thememaker.lockstyle.parsii.ExpressionUtils;
import com.thememaker.util.ThemeChangeUtils;
import com.thememaker.util.packager.LockScreenPackager;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.concurrent.Task;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ScrollPane;
import javafx.scene.image.Image;
import javafx.scene.layout.FlowPane;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.stage.Modality;
import javafx.stage.Stage;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.function.Consumer;

public class LockstyleIntentDialog {

    public LockstyleIntentDialog() {
    }

    public  void reviseIntent(File files, ThemeFileInfo themeFileInfo, String type, List<IntentCommand> error, Consumer<Path> consumer, Stage primaryStage,ExpressionUtils expressionUtils){
        File file = Paths.get(files.getPath()+File.separator+type+File.separator+"code").toFile();
        Stage stage = new Stage();
        stage.setResizable(false);
        stage.getIcons().add(new Image(
                getClass().getResourceAsStream(Context.getDrawable(R.drawable.launcher))));
        stage.setTitle("修改快捷");
        stage.initModality(Modality.APPLICATION_MODAL);
        stage.setMinWidth(790);
        stage.setMinHeight(480);
        stage.setMaxHeight(480);
        stage.setMaxWidth(790);
        ScrollPane scrollPane = new ScrollPane();
        FlowPane flowPane = new FlowPane();
        flowPane.setMinWidth(770);
        flowPane.setMaxWidth(780);
        flowPane.setHgap(18);
        flowPane.setVgap(18);
        flowPane.setPadding(new Insets(10, 10, 10, 10));
        error.forEach(e ->flowPane.getChildren().add(getImage(file,e,type,themeFileInfo,stage,flowPane,consumer,expressionUtils)));
        FlowPane flowPane2 = new FlowPane();
        flowPane2.setMinWidth(770);
        flowPane2.setMaxWidth(780);
        flowPane2.setHgap(18);
        flowPane2.setVgap(18);
        flowPane2.setPadding(new Insets(10, 10, 10, 10));
        List<IntentCommand> ohterList = IntentCommandUtils.getOther();
        ohterList.forEach(e ->flowPane2.getChildren().add(getImage(file,e,type,themeFileInfo,stage,flowPane,consumer,expressionUtils)));

        TitledPane needPane = getTitlePane("  需要修改：", flowPane);
        TitledPane noPane = getTitlePane("  已修改：", flowPane2);
        HBox hBox = new HBox();
        Button yesBtn = new Button("确认修改");
        yesBtn.setId("diy-button");
        yesBtn.setOnAction(event->{
            stage.close();
            ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                @Override
                protected Void call() throws Exception {
                    if (file != null) {
                        if(type.equals(Constants.OS360)){
                            IntentCommandUtils.copyFile(file, themeFileInfo, null);
                        }else{
                            ThemeChangeUtils.getInstance().copyManifestFile();
                        }
                    }
                    return null;
                }
            }, primaryStage, "正在转换，请稍等……");
            progressFrom.showProgressBar(() -> {
                if (file != null) {
                    Toast.makeText(primaryStage, "转换成功", 3000);
                    Platform.runLater(() -> {
                        if (IntentCommandUtils.getError().size() > 0) {
                            StringBuffer message = new StringBuffer("以下快捷修改失败，具体如下：\n");
                            for (IntentCommand in : IntentCommandUtils.getError()) {
                                message.append(JSON.toJSON(in) + "\n");
                            }
                            SBTFxDialog.showMessageDialog(primaryStage, message.toString(), "温馨提示");
                        }

                    });
                    try {
                        new LockScreenPackager(type, Paths.get(file.toString()),Paths.get(files.getPath(),type,"product","debug")).pack((types, path) -> {
                        }, (types, path) -> {
                        });
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    try {
                        File openFile =  Paths.get(files.getPath(),type,"product","debug").toFile();
                        Desktop.getDesktop().open(openFile);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            });
        });
        Button noBtn = new Button("    取消    ");
        noBtn.setId("diy-button");
        noBtn.setOnAction(event->{
            FileUtils.deleteDir(file);
            stage.close();
        });
        hBox.setAlignment(Pos.BOTTOM_CENTER);
        hBox.setSpacing(30);
        hBox.setPrefHeight(60);
        hBox.setPadding(new Insets(10, 10, 10, 10));
        hBox.getChildren().addAll(noBtn,yesBtn);
        Accordion accordion = new Accordion();
        accordion.setPadding(new Insets(10, 10, 10, 10));
        accordion.getPanes().addAll(needPane,noPane);
        accordion.setExpandedPane(needPane);
        accordion.setMinSize(760, 350);
        accordion.setMaxSize(790, 350);
        scrollPane.setContent(accordion);
        scrollPane.setMinSize(760, 400);
        scrollPane.setMaxSize(790, 400);
        VBox vBox = new VBox();
        vBox.getStylesheets().add("style/lockstylemain.css");
        vBox.getChildren().addAll(scrollPane,hBox);
        Scene scene = new Scene(vBox);
        stage.setScene(scene);
        stage.show();
        stage.setOnCloseRequest(event -> {
            System.err.println("删除文件");
            FileUtils.deleteDir(file);
            }
        );
    }

    public HBox getInfo(String text1,String text2){
        HBox hBox = new HBox();
        Label label = new Label(text1);
        label.setStyle("-fx-text-fill: #6E8BA9");
        Label label1 = new Label(text2);
        label1.setStyle("-fx-text-fill: #6E8BA9");
        hBox.getChildren().addAll(label,label1);
        return hBox;
    }

    public TitledPane getTitlePane(String title, FlowPane vBox) {
        TitledPane titledPane = new TitledPane(title, vBox);
        titledPane.setId("diy-center_titled_pane");
        titledPane.setStyle("-fx-text-fill: #716A94");
        return titledPane;
    }

    private VBox getImage(File file,IntentCommand e,String type,ThemeFileInfo themeFileInfo,Stage stage,FlowPane flowPane,Consumer<Path> consumer,ExpressionUtils expressionUtils) {
        VBox vBox = new VBox();
        vBox.setPadding(new Insets(10, 10, 10, 10));
        vBox.setSpacing(10);
        vBox.setAlignment(Pos.CENTER);
        vBox.setStyle("-fx-background-color: #eeeeee;");
        JFXComboBox comboBox =  new JFXComboBox();
        ObservableList<String> intList = FXCollections.observableArrayList();
        HBox hBox = new HBox();
        hBox.setMargin(comboBox,new Insets(-5,0,0,0));
        try {
            com.thememaker.lockstyle.bean.ui.Button btn = IntentCommandUtils.getIntentBtn(file,e.getImage_name().replace(".png","_btn").replace("\\","_"));
            Label label = new Label("快捷名：");
            String qikupath = String.valueOf(FileUtils.getResFileOfThemeModel(type, "launchpad"));
            Map<String, LaunchPad> chengeList = IntentCommandUtils.getChengeList(qikupath);
            chengeList.forEach((re,LaunchPad) -> {
                intList.add(re);
            });
            intList.add(e.getIndex());
            comboBox.setItems(intList);
            comboBox.setPrefWidth(90);
            String selectText=e.getIndex();
            comboBox.getSelectionModel().select(selectText);
            comboBox.getSelectionModel().selectedIndexProperty().addListener(new ChangeListener<Number>() {
                @Override
                public void changed(ObservableValue<? extends Number> observable, Number oldValue, Number newValue) {
                    if(oldValue.intValue()!=newValue.intValue()){
                        System.out.println(intList.get(newValue.intValue()));
                        ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                            @Override
                            protected Void call() throws Exception {
                                IntentCommandUtils.changeIntent(file,intList.get(oldValue.intValue()), intList.get(newValue.intValue()),themeFileInfo,qikupath,true);
                                return null;
                            }
                        }, stage, "正在修改快捷，请稍等……");
                        progressFrom.showProgressBar(() -> {
                            Toast.makeText(stage, "修改成功", 3000);
                        });
                    }
                }
            });
            label.setStyle("-fx-text-fill: #6E8BA9");
            hBox.getChildren().addAll(label,comboBox);
            Button deleBtn = new Button("删除");
            deleBtn.setId("diy-button");
            deleBtn.setAlignment(Pos.CENTER_LEFT);
            deleBtn.setOnAction(event->{
                ProgressDialog progressFrom = new ProgressDialog(new Task<Void>() {
                    @Override
                    protected Void call() throws Exception {
                        IntentCommandUtils.deleIntent(file,e.getImage_name().replace(".png","_btn").replace("\\","_"),e.getImage_name());
                        return null;
                    }
                }, stage, "正在删除快捷，请稍等……");
                progressFrom.showProgressBar(() -> {
                    Toast.makeText(stage, "删除成功", 3000);
                    flowPane.getChildren().remove(vBox);
                });

            });
            System.out.println(Paths.get(file.getPath())+File.separator+e.getImage_name());
            vBox.getStyleClass().addAll("custom-color-dialog");
            File file1 = new File(file+File.separator+e.getImage_name());
            BufferedImage sourceImg = null;
            if(file1.exists()){
                sourceImg = ImageIO.read(new FileInputStream(file1));
                vBox.getChildren().addAll(LayoutComponentUtils.getInstance().getImagePane(Paths.get(file.getPath()),100, 100,
                        Paths.get(file.getPath())+File.separator+e.getImage_name(),
                        0, 0, false, consumer),hBox,getInfo("图片尺寸：",Optional.ofNullable(sourceImg.getWidth()).orElse(0)+"*"+Optional.ofNullable(sourceImg.getHeight()).orElse(0)),getInfo("按钮位置：","x:"+expressionUtils.parseExpr(btn.getX())+"  y:"+expressionUtils.parseExpr(btn.getY())),getInfo("按钮大小：",btn.getW()+"*"+btn.getH()),deleBtn);

            }else{
                vBox.getChildren().addAll(LayoutComponentUtils.getInstance().getImagePane(Paths.get(file.getPath()),100, 100,
                        Paths.get(file.getPath())+File.separator+e.getImage_name(),
                        0, 0, false, consumer),hBox,getInfo("按钮位置：","x:"+expressionUtils.parseExpr(btn.getX())+"  y:"+expressionUtils.parseExpr(btn.getY())),getInfo("按钮大小：",btn.getW()+"*"+btn.getH()),deleBtn);

            }
       } catch (IOException e1) {
            e1.printStackTrace();
        }
        return vBox;
    }
}
